package com.idanchuang.support.mybatis.crypt.handler;

import com.idanchuang.support.mybatis.crypt.annotation.CryptField;
import com.idanchuang.support.mybatis.crypt.util.CryptUtil;

/**
 * 处理 String 对象的加解密
 *
 * @author kamjin1996
 */
public class StringCryptHandler implements CryptHandler<String> {

    @Override
    public Object encrypt(String param, CryptField cryptField) {
        if (needEncrypt(param, cryptField)) {
            return CryptUtil.encrypt(param);
        }
        return param;
    }

    private boolean needEncrypt(String param, CryptField cryptField) {
        return cryptField != null && cryptField.encrypt() && param != null && param.length() != 0;
    }

    private boolean needDecrypt(String param, CryptField cryptField) {
        return cryptField != null && cryptField.decrypt() && param != null && param.length() != 0;
    }

    @Override
    public Object decrypt(String param, CryptField cryptField) {
        if (needDecrypt(param, cryptField)) {
            return CryptUtil.decrypt(param);
        }
        return param;
    }
}
